//
//  ZYXDownloadImgViewController.m
//  MultiThreading
//  子线程和主线程通信
//

#import "ZYXDownloadImgViewController.h"

@interface ZYXDownloadImgViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation ZYXDownloadImgViewController

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    // 在子线程中调用download方法下载图片
    [self performSelectorInBackground:@selector(download) withObject:nil];
}

/**
 * 下载图片 : 子线程
 */
- (void)download
{
    // 1.根据URL下载图片
    NSURL *url = [NSURL URLWithString:@"https://git.oschina.net/uploads/87/338787_solozyx-iOS.jpg"];
    NSLog(@"-------begin");
    NSData *data = [NSData dataWithContentsOfURL:url]; // 这行会比较耗时
    NSLog(@"-------end");
    UIImage *image = [UIImage imageWithData:data];
    
    // 2.回到主线程显示图片
    //    [self.imageView performSelector:@selector(setImage:) onThread:[NSThread mainThread] withObject:image waitUntilDone:NO];

    [self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
    //    [self performSelectorOnMainThread:@selector(settingImage:) withObject:image waitUntilDone:NO];
}

/**
 * 设置(显示)图片: 主线程
 */
//- (void)settingImage:(UIImage *)image
//{
//    self.imageView.image = image
//}

@end
